#!/usr/bin/env node
const config = require("./config");
const exec = require("child_process").exec;
console.log("--- 开始上传 uniCloud 代码到网页托管 ---");

/**
 * 执行 npm
 */
function start(cmd = "") {
  // 任何你期望执行的cmd命令，ls都可以
  let workerProcess = exec(cmd, {
    cwd: config.cliPath,
  });
  return new Promise((resolve, reject) => {
    let content = [];
    // 打印正常的后台可执行程序输出
    workerProcess.stdout.on("data", function (data) {
      content = data.split(":");
      process.stdout.write(data);
    });
    // 打印错误的后台可执行程序输出
    workerProcess.stderr.on("data", function (data) {
      process.stdout.write(data);
      reject(data);
    });
    // 退出之后的输出
    workerProcess.on("close", function (code) {
      let ret = content.length > 0 && content[0];
      if (Number(ret) === 0) {
        resolve(content);
      } else if (ret === -1) {
        console.log("err", content, join(""));
        reject(content);
      }
    });
  });
}

let loginText = `./cli user login --username ${config.username} --password ${config.password} `;
start(loginText).then(async () => {
  console.log("账号登录成功 ：", config.username);
  let fromPath = config.distPath;
  let hostPath = `./cli hosting deploy --provider aliyun --space ${config.spaceid} --source`;

  let fileMap = config.fileMap;
  if (!fileMap || fileMap.length === 0) {
    console.log("开始上传整个目录到网页托管根目录：", fromPath);
    await start(`${hostPath} ${fromPath} --prefix /`);
    return;
  }

  for (let i = 0; i < fileMap.length; i++) {
    let file = fileMap[i];
    // 是否 / 结束
    let isEnd = file.endsWith("/");
    console.log("开始上传：", file);
    await start(
      `${hostPath} ${fromPath + file} --prefix ${isEnd ? file : "/"}`
    );
  }

  // start(`${hostPath} ${fromPath +'static/'} --prefix /static/`).then(()=>{
  // 	start(`${hostPath} ${fromPath + 'index.html'} --prefix /index.html`).then(()=>{
  // 		start(`${hostPath} ${fromPath + 'favicon.ico'} --prefix /favicon.ico`).then(()=>{

  // 		})
  // 	})
  // })
});
// start('./cli user login --username unicloudService@dcloud.io  --password 9defbcg').then(()=>{

// })
